﻿#include "Sensor.h"
#include <wiringPi.h>
#include <unistd.h>

Sensor::Sensor(int deviceID, std::string dbName, std::string dataTableName, std::string configTableName)
	:deviceID(deviceID), buffer(deviceID,dbName ,configTableName,dataTableName)
{
	if (-1 == wiringPiSetup())
	{
		cerr <<"wiringPi 初始化失败\n";
	}
	//buffer.open(dbName);


}


Sensor::~Sensor()
{
	//buffer.close();
}

void Sensor::setConfig(const SensorConfig& config)
{
	this->config = config;
}

unsigned int Sensor::ADC_Read(unsigned char channel)
{
    unsigned int value;
    unsigned char i;
    unsigned char LSB = 0, MSB = 0;

    channel = channel << 4;
    for (i = 0; i < 4; i++)
    {
        if (channel & 0x80)
            digitalWrite(Address, 1);
        else
            digitalWrite(Address, 0);
        digitalWrite(Clock, 1);
        digitalWrite(Clock, 0);
        channel = channel << 1;
    }
    for (i = 0; i < 6; i++)
    {
        digitalWrite(Clock, 1);
        digitalWrite(Clock, 0);
    }

    delayMicroseconds(15);
    for (i = 0; i < 2; i++)
    {
        digitalWrite(Clock, 1);
        MSB <<= 1;
        if (digitalRead(DataOut))
            MSB |= 0x1;
        digitalWrite(Clock, 0);
    }
    for (i = 0; i < 8; i++)
    {
        digitalWrite(Clock, 1);
        LSB <<= 1;
        if (digitalRead(DataOut))
            LSB |= 0x1;
        digitalWrite(Clock, 0);
    }
    value = MSB;
    value <<= 8;
    value |= LSB;
    return value;
}

SensorConfig SensorConfig::operator=(const SensorConfig& config)
{
	this->sample = config.sample;
	return *this;
}
